<template>
  <div class="datasetting p-2">
    <a-form-item label="数据来源">
      <a-select size="small" v-model="currentComponent.data.source">
        <a-option value="cube" label="数据集">数据集</a-option>
        <a-option v-if="setting.apiConfig" value="api" label="api接口">API</a-option>
      </a-select>
    </a-form-item>
    <a-form-item :label="currentComponent.data.source === 'cube' ? '数据集' : 'api'" content-class="gap-2">
      <a-select v-model="currentComponent.data.cube_id" allow-search allow-clear>
        <a-option v-for="item in cubeList" :key="item.id" :value="item.id" :label="item.name" />
      </a-select>
      <a-button size="mini" @click="cubeEdit">编辑</a-button>
      <a-button size="mini" status="success" @click="init">刷新</a-button>
    </a-form-item>

    <div class="h-full" style="height: calc(100% - 145px)" :class="visible ? 'flex justify-between' : ''">
      <div class="p-2 h-full" :class="visible ? 'w-3/5' : ''">
        <div class="overflow-y-auto h-full" style="height: calc(100vh - 270px)">
          <template v-for="(item, key) in setting.dataConfigOption" :key="item.name">
            <div class="flex justify-between">
              <div>
                {{ item.name }}/{{ item.type === "dimension" ? "维度" : "指标" }}
                {{ currentComponent.data[key]?.length || 0 }}/{{ item.max }}
              </div>
              <a-button
                :type="formFields.key === key ? 'primary' : 'dashed'"
                @click="changeField(item.type, key)"
                size="mini"
              >
                选择字段 <span class="bi-arrow-right-double-line" />
              </a-button>
            </div>
            <div
              :style="`max-height: ${item.max === 1 ? 36 : 300}px;min-height: 32px`"
              class="overflow-auto border border-dashed mb-2"
            >
              <draggable v-model="currentComponent.data[key]" class="layer-list" item-key="field" :animation="200">
                <template #item="{ element, index }">
                  <div class="border-black-400 m-1 px-2 border-2 flex justify-between">
                    <a-tooltip :content="element.field" position="left" show-arrow>
                      <template #content>
                        <div>原始字段名称</div>
                        <div>{{ element.field }} {{ element.title }}</div>
                      </template>
                      <span>
                        {{ element.title }}
                        {{ element.type === "M" ? "(" + aggregateTypeMapFind(element.aggregate) + ")" : "" }}
                      </span>
                    </a-tooltip>
                    <a-space size="mini">
                      <a-popover :content-style="{ width: '260px' }" position="bottom" show-arrow trigger="click">
                        <template #content>
                          <a-form label-width="85px" auto-label-width>
                            <a-form-item label="显示名称">
                              <a-input v-model="element.title" size="small" />
                            </a-form-item>
                            <!--                            {{ element }}-->
                            <a-form-item v-if="element.dataType.includes('yy')" label="日期展示格式">
                              <a-select size="small" v-model="element.dataType" placeholder="请选择聚合方式" auto-width>
                                <a-option
                                  v-for="item in fieldDateFormats"
                                  :key="item.value"
                                  :value="item.value"
                                  :label="item.label"
                                  :disabled="item.value === ''"
                                />
                              </a-select>
                            </a-form-item>
                            <a-form-item v-if="element.type === 'M'" label="聚合方式">
                              <a-select
                                size="small"
                                v-model="element.aggregate"
                                placeholder="请选择聚合方式"
                                auto-width
                              >
                                <a-option
                                  v-for="item in aggregateTypeMap"
                                  :key="item.value"
                                  :value="item.value"
                                  :label="item.label"
                                  :disabled="item.value === ''"
                                />
                              </a-select>
                            </a-form-item>
                            <a-form-item v-if="element.type === 'M'" label="数值展示格式">
                              <a-select
                                size="small"
                                v-model="element.format"
                                placeholder="请选择数值展示格式"
                                auto-width
                              >
                                <a-option
                                  v-for="item in fieldNumberFormats"
                                  :key="item.value"
                                  :value="item.value"
                                  :label="item.label"
                                />
                              </a-select>
                            </a-form-item>
                            <a-form-item v-if="element.format === 'CUSTOM'" label="公式" help="例如/100, *1000">
                              <a-textarea v-model="element.official" />
                            </a-form-item>
                            <a-form-item v-if="element.official" label="位数">
                              <a-input-number v-model="element.digits" step="1" />
                            </a-form-item>
                          </a-form>
                        </template>
                        <span class="bi-settings-2-line ml-1 cursor-pointer" />
                      </a-popover>
                      <a-tooltip content="删除" placement="top" show-arrow>
                        <span class="bi-close-line ml-1 cursor-pointer" @click="deleteField(index, key)" />
                      </a-tooltip>
                    </a-space>
                  </div>
                </template>
              </draggable>
            </div>
          </template>
          <a-space class="flex justify-between">
            <div>排序</div>
            <a-button
              :type="formFields.key === 'sort' ? 'primary' : 'dashed'"
              @click="changeField('sort', 'sort', 'sort')"
              size="mini"
            >
              选择字段 <span class="bi-arrow-right-double-line" />
            </a-button>
          </a-space>
          <div :style="`min-height: 30px`" class="overflow-auto border border-dashed mb-2">
            <draggable v-model="currentComponent.data.sort" class="layer-list" item-key="field" :animation="200">
              <template #item="{ element, index }">
                <div class="border-black-400 m-1 px-2 border-2 flex justify-between">
                  <a-tooltip :content="element.name" position="left" show-arrow>
                    <template #content>
                      <div>原始字段名称</div>
                      <div>{{ element.field }} {{ element.title }}</div>
                    </template>
                    <span class="mr-2">{{ element.title }}</span>
                  </a-tooltip>
                  <a-space size="small">
                    <div
                      class="cursor-pointer"
                      :class="element.sort === 'desc' ? 'bi-sort-desc' : 'bi-sort-asc'"
                      @click="element.sort = element.sort === 'asc' ? 'desc' : 'asc'"
                    />
                    <a-tooltip content="删除" placement="top" show-arrow>
                      <span class="bi-close-line ml-1 cursor-pointer" @click="deleteField(index, 'sort')" />
                    </a-tooltip>
                  </a-space>
                </div>
              </template>
            </draggable>
          </div>
          <a-space class="flex justify-between">
            <div>过滤条件</div>
            <a-button
              :type="formFields.key === 'filter' ? 'primary' : 'dashed'"
              @click="changeField('filter', 'filter', 'filter')"
              size="mini"
            >
              选择字段 <span class="bi-arrow-right-double-line" />
            </a-button>
          </a-space>
          <div :style="`min-height: 30px`" class="overflow-auto border border-dashed mb-2">
            <draggable v-model="currentComponent.data.filter" class="layer-list" item-key="field" :animation="200">
              <template #item="{ element, index }">
                <div class="border-black-400 m-1 px-2 border-2 flex justify-between">
                  <a-tooltip :content="element.name" position="left" show-arrow>
                    <template #content>
                      <div>原始字段名称</div>
                      <div>{{ element.field }} {{ element.title }}</div>
                    </template>
                    {{ element.title }}
                    {{ element.type === "M" ? "(" + aggregateTypeMapFind(element.aggregate) + ")" : "" }}
                  </a-tooltip>
                  <a-space size="small">
                    <a-dropdown v-if="element.type === 'M'">
                      <template #content>
                        <template
                          v-for="item in aggregateTypeMap.map((v) => {
                            return { label: v.label, value: v.value }
                          })"
                          :key="item.value"
                        >
                          <a-doption
                            @click="
                              (e) => {
                                element.aggregate = item.value
                              }
                            "
                          >
                            {{ item.label }}
                          </a-doption>
                        </template>
                      </template>
                      <div class="cursor-pointer bi-equalizer-line" />
                    </a-dropdown>
                    <div
                      class="cursor-pointer"
                      title="设置过滤条件"
                      :class="element?.filter ? 'bi-filter-fill text-blue-800' : 'bi-filter-line'"
                      @click="setFilter(element)"
                    />
                    <a-tooltip content="删除" placement="top" show-arrow>
                      <span class="bi-close-line ml-1 cursor-pointer" @click="deleteField(index, 'filter')" />
                    </a-tooltip>
                  </a-space>
                </div>
              </template>
            </draggable>
            <Filter :filterItem="setFilterForm" v-model:visible="setFilterVisible" />
          </div>
        </div>
        <div class="p-2 border-t-2">
          <div class="flex items-center">
            结果展示：
            <a-input-number v-model="currentComponent.data.page_size" size="small" style="width: 160px">
              <template #suffix> /条 </template>
            </a-input-number>
          </div>
          <div class="gap-2 flex-between mt-1">
            <a-checkbox v-model="currentComponent.data.isPollingInterval">自动刷新</a-checkbox>
            <a-input-number
              v-if="currentComponent.data.isPollingInterval"
              style="width: 60%"
              size="small"
              v-model="currentComponent.data.pollingInterval"
              theme="normal"
              placeholder="自动刷新时间"
              suffix="/s"
              min="0"
            />
          </div>
          <div class="gap-2 flex-between mt-1">
            <a-button size="small" type="primary" @click="previewData(currentComponent)" long>预览刷新</a-button>
          </div>
        </div>
      </div>
      <div
        v-if="visible"
        class="h-[99%] pt-2.5 pl-1 overflow-hidden border-l-4 divide-y divide-dashed flex-1"
        style="width: 160px"
      >
        <a-space>
          <a-input-search allow-clear size="mini" @input="searchAllFields" placeholder="搜索字段" />
          <a-button size="mini" type="dashed" @click="changeField('close')">关闭</a-button>
        </a-space>
        <a-space class="my-2">
          <a-button size="mini" v-if="showAddAll" type="dashed" @click="selectField('all')">添加全部</a-button>
          <a-button size="mini" type="dashed" @click="selectField('clear')">清空选中</a-button>
        </a-space>
        <div class="overflow-auto h-[calc(100%-60px)]">
          <a-button
            :disabled="isSelect(item)"
            class="p-1 py-2 text-xs cursor-alias text-left truncate hover:bg-blue-400 border-dashed border-y w-full justify-start"
            v-for="item in allFieldsList"
            :key="item.field"
            @click="selectField(item)"
            :title="item.title + item.field"
          >
            <span :class="item.type === 'D' ? 'text-green-700' : 'text-red-900'">
              {{ item.type === "D" ? "[维度]" : "[指标]" }}
            </span>
            {{ item.title }}
            {{ item.field }}
          </a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import draggable from "vuedraggable"
import { useComponent } from "@/hooks/userEditor"
import {
  dimension,
  cubeList,
  getCubeList,
  getDataCubeDetail,
  cubeDetail,
  searchAllFields
} from "@/hooks/useDataCube.js"

const { currentComponent, previewData } = useComponent()
import { settings } from "@/plugins/index.js"
import { Message } from "@arco-design/web-vue"
import Filter from "@/views/visual/screen/filter.vue"
import { aggregateTypeMap, aggregateTypeMapFind, fieldDateFormats, fieldNumberFormats } from "@/utils/dict"

const setting = settings.value[currentComponent.value.name]
const init = () => {
  if (currentComponent.value.data.source === "cube") {
    getCubeList({
      page: 1,
      page_size: 100,
      search: ""
    })
    if (currentComponent.value.data.cube_id) {
      getDataCubeDetail(currentComponent.value.data.cube_id)
    }
  }
}
init()
// 切换数据来源
watch(
  () => currentComponent.value.data.source,
  (val) => {
    if (val === "cube") {
      getCubeList({
        saiType: "all"
      })
    }
  }
)
watch(cubeDetail, (val) => {
  dimension.value = []
  currentComponent.value.data.datasource_id = val.datasource_id
  dimension.value = val.fields
  currentComponent.value.data.fields = dimension.value
})
watch(
  () => currentComponent.value.data.cube_id,
  (val, oldValue) => {
    if (val && val !== oldValue) {
      init()
    }
  }
)

// 选择数据
const visible = ref(false)
// 字段列表
const allFields = computed(() => {
  return {
    dimension: dimension.value.filter((item) => item.type === "D"),
    measure: dimension.value.filter((item) => item.type === "M")
  }
})
const allFieldsList = computed(() => {
  const val = formFields.value.type
  if (val === "sort" || val === "filter") {
    return [...allFields.value.dimension, ...allFields.value.measure]
  }
  return allFields.value[formFields.value.type]
})
const formFields = ref({
  type: "dimension",
  key: ""
})

const changeField = (val, key) => {
  const settingsDom = document.querySelector("#settings")
  const canvasEditRefDom = document.querySelector("#canvasEditRef")
  if (val === "close") {
    closeField()
    return
  }
  formFields.value.type = val
  formFields.value.key = key
  visible.value = true
  settingsDom.style.width = 550 + "px"
  canvasEditRefDom.style.width = "calc(100% - 600px)"
}

// 关闭选择字段
const closeField = () => {
  const settingsDom = document.querySelector("#settings")
  const canvasEditRefDom = document.querySelector("#canvasEditRef")
  visible.value = false
  settingsDom.style.width = 330 + "px"
  canvasEditRefDom.style.width = "calc(100% - 550px)"
  formFields.value.type = ""
  formFields.value.key = ""
}

// 选择字段事件
const selectField = (item) => {
  item = JSON.parse(JSON.stringify(item))
  const fields = currentComponent.value.data[formFields.value.key]
  if (item === "clear") {
    currentComponent.value.data[formFields.value.key] = []
    return
  }
  if (item === "all") {
    allFieldsList.value.map((itemm, index) => {
      itemm.key = formFields.value.key
      if (index >= setting.dataConfigOption[itemm.key]?.max) {
        return
      }
      currentComponent.value.data[formFields.value.key].push(itemm)
    })
    return
  }
  item.key = formFields.value.key
  if (setting.dataConfigOption[item.key]?.max === 1) {
    currentComponent.value.data[formFields.value.key] = [item]
    return
  }
  if (setting.dataConfigOption[item.key] && fields.length >= setting.dataConfigOption[item.key].max) {
    // 提示
    MessagePlugin.error(
      `最多选择${setting.dataConfigOption[item.key].max}个${item.type === "dimension" ? "维度" : "指标"}`
    )
    return
  }
  if (formFields.value.key === "sort") {
    item.sort = "asc"
  }
  currentComponent.value.data[formFields.value.key].push(item)
}
// 判断字段是否选择
const isSelect = (item) => {
  const fields = currentComponent.value.data[formFields.value.key]
  return fields.some((v) => v.field === item.field)
}
// 删除字段
const deleteField = (index, key) => {
  const fields = currentComponent.value.data[key]
  fields.splice(index, 1)
}

// 判断是否显示添加全部
const showAddAll = computed(() => {
  return setting.dataConfigOption[formFields.value.key]?.max > 5
})

// 离开页面
onUnmounted(() => {
  closeField()
})

const router = useRouter()
const cubeEdit = () => {
  const cubeId = currentComponent.value.data.cube_id
  if (!cubeId) {
    Message.error("请先选择数据集")
    return
  }
  // 跳转数据集编辑页
  const route = router.resolve({
    path: "/cubeeditor",
    query: {
      id: cubeId
    }
  })
  window.open(route.href, "_blank")
}

// 设置过滤条件
const setFilterVisible = ref(false)
const setFilterForm = ref({})
const setFilter = (item) => {
  setFilterForm.value = item
  setFilterVisible.value = true
}
</script>

<style scoped lang="less">
.datasetting {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
:deep(.t-form__item) {
  @apply mb-1;
}
</style>
